package com.jwaoo.chat.viewholder;

import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.dx.as.common.log.LogUtil;
import com.dx.as.common.string.StringUtil;
import com.dx.as.common.sys.ScreenUtil;
import com.dx.as.upload.DownloadManager;
import com.dx.as.upload.OnDownloadListener;
import com.jwaoo.chat.ChatConstants;
import com.jwaoo.chat.R;
import com.jwaoo.chat.attachment.FileAttachment;
import com.jwaoo.chat.bitmap.BitmapDecoder;
import com.jwaoo.chat.bitmap.ImageUtil;
import com.jwaoo.chat.data.db.MessageHandler;
import com.jwaoo.chat.ui.imageview.MsgThumbImageView;
import com.jwaoo.chat.ui.recyclerview.adpter.BaseMultiItemFetchLoadAdapter;

import java.io.File;

/**
 * Created by zhoujianghua on 2015/8/4.
 */
public abstract class MsgViewHolderThumbBase extends MsgViewHolderBase {

    public MsgViewHolderThumbBase(BaseMultiItemFetchLoadAdapter adapter) {
        super(adapter);
    }

    protected MsgThumbImageView thumbnail;
    protected View progressCover;
    protected TextView progressLabel;

    @Override
    protected void inflateContentView() {
        thumbnail = findViewById(R.id.message_item_thumb_thumbnail);
        thumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onItemClick();
            }
        });
        progressBar = findViewById(R.id.message_item_thumb_progress_bar); // 覆盖掉
        progressCover = findViewById(R.id.message_item_thumb_progress_cover);
        progressLabel = findViewById(R.id.message_item_thumb_progress_text);

    }

    @Override
    protected void bindContentView() {
        FileAttachment msgAttachment =  message.getAttachment();
        String path = msgAttachment.getPath();
        String thumbPath = msgAttachment.getThumbPath();
//        String thumbPath = msgAttachment.getThumbnail();
        if (!TextUtils.isEmpty(thumbPath)) {
            loadThumbnailImage(thumbPath, false);
        } else if (!TextUtils.isEmpty(path)) {
            loadThumbnailImage(thumbFromSourceFile(path), true);
        } else {
            String thumbnailPth = msgAttachment.getThumbnail();
            loadThumbnailImage(thumbnailPth, false);

        }
        refreshStatus();
        downLoad();
    }

    private void refreshStatus() {
        FileAttachment attachment = message.getAttachment();
//        if (TextUtils.isEmpty(attachment.getPath()) && TextUtils.isEmpty(attachment.getThumbPath())) {
//            if (message.getAttachment().getAttachstate() == ChatConstants.fail || message.getState() == ChatConstants.fail) {
//                alertButton.setVisibility(View.VISIBLE);
//            } else {
//                alertButton.setVisibility(View.GONE);
//            }
//        }

        if ((message.getState() == ChatConstants.sending
                || (isReceivedMessage() && message.getAttachment().getAttachstate() == ChatConstants.transferring)) && message.getDirect() == ChatConstants.Out) {
            progressCover.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.VISIBLE);
            progressLabel.setVisibility(View.VISIBLE);
            progressLabel.setText(getMsgAdapter().getProgress(message)+"");
        } else {
            progressCover.setVisibility(View.GONE);
            progressBar.setVisibility(View.GONE);
            progressLabel.setVisibility(View.GONE);
        }
    }

    private void downLoad(){
        if (message.getAttachment().getAttachstate() == ChatConstants.transferred || message.getDirect() == ChatConstants.In) return;
        if (!DownloadManager.isDownloading(message.getMsgid())){
            MessageHandler.getInstace(context).uploadAttachmentMessage(message);
        }
        DownloadManager.addDownloadListener(message.getMsgid(), new OnDownloadListener() {
            @Override
            public void onDownloadFailed() {
                message.getAttachment().setAttachstate(ChatConstants.fail);
            }

            @Override
            public void onDownSuccess() {
                message.getAttachment().setAttachstate(ChatConstants.transferred);
            }

            @Override
            public void onDownProgress(final long progress,final long total) {
                getMsgAdapter().getHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        progressLabel.setText(StringUtil.getPercentString(progress * 100/total));
                        LogUtil.d("SnapChat",StringUtil.getPercentString(progress * 100/total));
                    }
                });
            }
        });
    }

    private void loadThumbnailImage(String path, boolean isOriginal) {
        setImageSize(path);
        if (path != null) {
            //thumbnail.loadAsPath(thumbPath, getImageMaxEdge(), getImageMaxEdge(), maskBg());
            thumbnail.loadAsPath(isOriginal, path, message.getMsgid()+"", getImageMaxEdge(), getImageMaxEdge(), maskBg());
        } else {
            thumbnail.loadAsResource(R.drawable.nim_image_default, maskBg());
        }
    }

    private void setImageSize(String thumbPath) {
        int[] bounds = null;
        if (thumbPath != null && !thumbPath.contains("http://") && !thumbPath.contains("https://")) {
            bounds = BitmapDecoder.decodeBound(new File(thumbPath));
        }
        if (bounds == null) {
            FileAttachment attachment = message.getAttachment();
            bounds = new int[]{attachment.getWidth(), attachment.getHeight()};
        }

        if (bounds != null) {
            ImageUtil.ImageSize imageSize = ImageUtil.getThumbnailDisplaySize(bounds[0], bounds[1], getImageMaxEdge(), getImageMinEdge());
            setLayoutParams(imageSize.width, imageSize.height, thumbnail);
        }
    }

    private int maskBg() {
        return R.drawable.nim_message_item_round_bg;
    }

    public static int getImageMaxEdge() {
        return (int) (165.0 / 320.0 * ScreenUtil.screenWidth);
    }

    public static int getImageMinEdge() {
        return (int) (76.0 / 320.0 * ScreenUtil.screenWidth);
    }

    protected abstract String thumbFromSourceFile(String path);
}
